#!/usr/bin/env python
# -* - coding: utf - 8 -* -
import hashlib
import json
import requests
from alipay.aop.api.AlipayClientConfig import AlipayClientConfig
from alipay.aop.api.DefaultAlipayClient import DefaultAlipayClient
from alipay.aop.api.domain.AlipayTradeWapPayModel import AlipayTradeWapPayModel
from alipay.aop.api.request.AlipayTradeWapPayRequest import AlipayTradeWapPayRequest

from h5api.settings import ALIPAY_ADD_ID, ALIPAY_APP_PRIVATE_KEY, ALIPAY_PUBLIC_KEY


#支付宝退款
def refound(trade_no,refound_amount,out_request_no):
    """ 初始化 """
    alipay_client_config = AlipayClientConfig()

    """ 支付宝网关 """
    alipay_client_config.server_url = 'https://openapi.alipay.com/gateway.do'
    alipay_client_config.app_id =   ALIPAY_ADD_ID
    alipay_client_config.app_private_key = ALIPAY_APP_PRIVATE_KEY
    alipay_client_config.alipay_public_key =  ALIPAY_PUBLIC_KEY



    """ 签名算法类型 """
    alipay_client_config._sign_type = 'RSA2'
    client = DefaultAlipayClient(alipay_client_config, None)
    
    """ 构造请求参数对象，当前调用接口名称：alipay.trade.wap.pay(手机网站支付接口) """ 
    model = AlipayTradeWapPayModel()
    
    model.out_request_no = out_request_no
    
    model.refound_amount = refound_amount
    
    """ 订单标题 """ 
    model.trade_no = trade_no
    
    

    request = AlipayTradeRefundRequest(biz_model=model)
    
    
        
    """ 调用SDK生成form表单 """
    # response = client.page_execute(request)
    
    """ 调用SDK生成支付链接，可在浏览器打开链接进入支付页面 """
    response = client.page_execute(request,http_method="GET")
    
    
#检测回调内容
def getPayLinkAliPay(alipay,goods,orderId,callbackUrl,returnUrl=""):

    """ 初始化 """
    alipay_client_config = AlipayClientConfig()

    """ 支付宝网关 """
    alipay_client_config.server_url = 'https://openapi.alipay.com/gateway.do'
    alipay_client_config.app_id = alipay.appId or ALIPAY_ADD_ID
    alipay_client_config.app_private_key = alipay.privateKey or ALIPAY_APP_PRIVATE_KEY
    alipay_client_config.alipay_public_key = alipay.publicKey or ALIPAY_PUBLIC_KEY



    """ 签名算法类型 """
    alipay_client_config._sign_type = 'RSA2'
    client = DefaultAlipayClient(alipay_client_config, None)
    
    """ 构造请求参数对象，当前调用接口名称：alipay.trade.wap.pay(手机网站支付接口) """ 
    model = AlipayTradeWapPayModel()
    
    """ 商户订单号，商户自定义，需保证在商户端不重复，如：20200612000001 """ 
    model.out_trade_no = orderId
    
    """ 订单金额，精确到小数点后两位 """ 
    model.total_amount = goods["sellPrice"]
    
    """ 订单标题 """ 
    model.subject = goods["goodsName"]
    
    """销售产品码，固定值：QUICK_WAP_WAY """ 
    model.product_code="QUICK_WAP_WAY"; 

    model.passback_params = orderId
    
    
    

    request = AlipayTradeWapPayRequest(biz_model=model)
    
    """注：支付结果以异步通知为准，不能以同步返回为准，因为如果实际支付成功，但因为外力因素，如断网、断电等导致页面没有跳转，则无法接收到同步通知；"""
    """支付完成的跳转地址,用于用户视觉感知支付已成功，传值外网可以访问的地址，如果同步未跳转可参考该文档进行确认：https://opensupport.alipay.com/support/helpcenter/193/201602474937 """
    request.return_url=returnUrl
    
    """ 异步通知地址，商户外网可以post访问的异步地址，用于接收支付宝返回的支付结果，如果未收到该通知可参考该文档进行确认：https://opensupport.alipay.com/support/helpcenter/193/201602475759 """ 
    request.notify_url=callbackUrl
        
        
    """ 调用SDK生成form表单 """
    # response = client.page_execute(request)
    
    """ 调用SDK生成支付链接，可在浏览器打开链接进入支付页面 """
    response = client.page_execute(request,http_method="GET")
    
    """获取接口调用结果，如果调用失败，可根据返回错误信息到该文档寻找排查方案：https://opensupport.alipay.com/support/helpcenter/101 """ 
    return response 

def sign(*p):
    res = hashlib.md5(u''.join(p).encode('utf8')).hexdigest().lower()
    return res

def getPayLinkXorPay(xorpay,goods,orderId,callback):

    payData = {
        'name':goods["goodsName"],
        'pay_type':"alipay",
        'price':str(goods["sellPrice"]),
        'order_id':str(orderId),
        'notify_url':callback,
        'more':str(orderId) 
    }

    payData['sign'] = sign(payData['name'],payData['pay_type'],payData['price'],payData['order_id'],payData['notify_url'],xorpay.privateKey)
    resp = requests.post("https://xorpay.com/api/pay/"+xorpay.appId,data=payData)
    # resp = requests.post("https://xorpay.com/api/pay/15526",data=payData)
    res = json.loads(resp.text)
    return res 

#查询订单状态
def query(aoid):
    resp = requests.get("https://xorpay.com/api/query/"+aoid)
    return json.loads(resp.text)